package com.yxplearn.mybatisplus.mybatis_sample;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Properties;

@Intercepts(
        /**
         * 拦截器签名 type, method对应其方法
         * org.apache.ibatis.executor.Executor
         * org.apache.ibatis.executor.parameter.ParameterHandler
         * org.apache.ibatis.executor.resultset.ResultSetHandler
         * org.apache.ibatis.executor.statement.StatementHandler
         *
         *
        */
        @Signature(type = Executor.class, method = "query", args = {
                MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class
        }))
public class SimpleInterceptor implements Interceptor {

    private String name;

    public SimpleInterceptor(String name) {
        this.name = name;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("intercept 执行前" + name);
        // 获取需要拦截的方法
        Method method = invocation.getMethod();
        // 获取需要拦截的对象
        Executor executor = (Executor) invocation.getTarget();
        // 获得拦截器的参数 4或者6个
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];

        BoundSql boundSql = ms.getBoundSql(parameter);
        String sql = boundSql.getSql();
        StringBuilder stringBuilder = new StringBuilder(sql);
        if (sql.contains("where")) {
            stringBuilder.append("\n and 1 = 1");
        } else {
            stringBuilder.append("\n where id = 4");
        }
        BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), stringBuilder.toString(), boundSql.getParameterMappings(), parameter);
        CacheKey cacheKey = executor.createCacheKey(ms, parameter, rowBounds, pageBoundSql);
        List<Object> query = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, pageBoundSql);
        System.out.println("intercept 执行前" + name);
        return query;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        properties.setProperty("name", "xxppx");
        properties.setProperty("email", "Ffxxs");
    }
}
